package com.alipay.freeblog.velocity.resource;

import com.alipay.freeblog.dal.daoobject.TemplateDO;
import com.alipay.freeblog.dal.interfaces.TemplateDao;
import com.ibatis.sqlmap.client.SqlMapClient;
import org.apache.commons.collections.ExtendedProperties;
import org.apache.log4j.Logger;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.resource.Resource;
import org.apache.velocity.runtime.resource.loader.ResourceLoader;
import org.apache.velocity.util.ExceptionUtils;
import org.springframework.stereotype.Component;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.Date;

/**
 * Velocity resource加载的Ibatis实现
 * Created by IntelliJ IDEA.
 * User: ning.ln
 * Date: 11-9-24
 * Time: 下午4:38
 */
@Component("iBatisResourceLoader")
public class IBatisResourceLoader extends ResourceLoader {

	/**
	 * template
	 */
	private TemplateDao templateDao;

	@Override
	public void init(ExtendedProperties configuration) {
		//do noting
	}

	/**
	 * 得到最近更新的时间
	 * */
	@Override
	public long getLastModified(Resource resource) {
		long time = 0;
		String source = resource.getName();
		try {
			Date gmt_update = templateDao.getTemplateByName(source).getGmt_update();
			time = gmt_update.getTime();
		} catch (Exception e) {
			throw new ResourceNotFoundException("getTemplateByName source=" + source + " error", e);
		}
		return time;
	}

	@Override
	public boolean isSourceModified(Resource resource) {
		return (resource.getLastModified() != getLastModified(resource));
	}


	/**
	 * 得到模版的stream
	 * */
	@Override
	public InputStream getResourceStream(String source) throws ResourceNotFoundException {
		String vm = null;
		InputStream in = null;
		try {
			TemplateDO templateDO = templateDao.getTemplateByName(source);
			vm = templateDO.getVm();
			in = new BufferedInputStream(new ByteArrayInputStream(vm.getBytes()));
		} catch (Exception e) {
			throw new ResourceNotFoundException("getTemplateByName source=" + source + " error", e);
		}
		return in;
	}

	public TemplateDao getTemplateDao() {
		return templateDao;
	}

	public void setTemplateDao(TemplateDao templateDao) {
		this.templateDao = templateDao;
	}
}
